import { useHistory, useLocation } from 'react-router-dom'
import { NavBar, InfiniteScroll } from 'antd-mobile'

import styles from './index.module.scss'
import { useDispatch, useSelector } from 'react-redux'
import ArticleItem from '@/pages/Home/components/ArticleItem'
import { useEffect, useState } from 'react'
import {
  clearResHistoryAction,
  searchResHistoryAction,
} from '@/store/action/search'
import { RootState } from '@/types/store'
const Result = () => {
  const history = useHistory()
  const dispatch = useDispatch()
  const location = useLocation()
  const [page, setPage] = useState(1)
  const per_page = 10
  const { res, search_total } = useSelector(
    (state: RootState) => state.searchReducer.searchResults
  )
  // 获取路由传参
  const params = new URLSearchParams(location.search)
  const q = params.get('q') as string

  // 上拉加载
  const [hasMore, setHasMore] = useState(true)
  async function loadMore() {
    await dispatch(searchResHistoryAction({ q, page, per_page }))
    setPage(page + 1)
  }
  useEffect(() => {
    return () => {
      dispatch(clearResHistoryAction())
    }
  }, [])
  useEffect(() => {
    if (search_total === -1) return
    if (res.length >= search_total) {
      setHasMore(false)
    }
  }, [res, search_total])
  return (
    <div className={styles.root}>
      <NavBar onBack={() => history.go(-1)}>搜索结果{search_total}</NavBar>
      <div className="article-list">
        <div className="article-item">
          {res.length > 0 &&
            res.map((v) => {
              return <ArticleItem key={v.art_id} item={v}></ArticleItem>
            })}
        </div>
        <InfiniteScroll loadMore={loadMore} hasMore={hasMore}></InfiniteScroll>
      </div>
    </div>
  )
}

export default Result
